package com.jt.www.common.controller;

import com.jt.www.common.service.CommonService;
import com.jt.www.domain.dto.UserBranchAndProvCode;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.util.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 通用接口
 */
@Api(value = "通用接口", tags = {"COMMON-API"}, description = "通用接口")
@RestController
@RequestMapping(value = "/common")
public class CommonController {

    public static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private CommonService commonService;

    @ApiOperation(value = "得到下一个整点", httpMethod = "GET")
    @GetMapping(value = "/nextHourTime", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> nextHourTime() throws Exception {
        String nextTime = commonService.nextHourTime();
        return GenericDataResponse.okWithData(nextTime);
    }


    @ApiOperation(value = "得到当前系统时间", httpMethod = "GET")
    @GetMapping(value = "/newTime", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> newTime() throws Exception {
        return GenericDataResponse.okWithData(DateUtils.converDate(new Date()));
    }

    /**
     * 通过用户查询线下录入的产品列表
     *
     * @return
     */
    @ApiOperation(value = "通过用户及分支机构名称模糊查询分支机构列表", notes = "通过用户及分支机构名称模糊查询分支机构列表", httpMethod = "GET")
    @GetMapping(value = "/getBranchList", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericDataResponse<UserBranchAndProvCode>> getBranchList(
            @RequestHeader("jtpf.userId") @ApiParam(value = "token解析的userId", required = true) String userCode,
            @ApiParam(value = "分支机构名称") @RequestParam(required = false) String branchName) {
        String findCode = "OfflineProductList_" + System.currentTimeMillis();
        log.info("{} 通过用户及分支机构名称模糊查询分支机构列表, userCode:{}, branchName:{}", findCode, userCode, branchName);
        try {
            if (StringUtils.isNotBlank(userCode)) {
                return commonService.getBranchList(findCode, userCode, branchName);
            }
        } catch (Exception e) {
            log.error("{} 异常:{} ", findCode, e.getMessage(), e);
        }

        return GenericDataResponse.okWithData(new UserBranchAndProvCode());
    }
}
